Dashboard Temp Share Shortlinks Frames API

HTMLify

Reverse Words in a String.cpp
Views: 1 | Author: cody
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
    string reverseWords(string s) {
        int n = s.length();
        string ans = "";
        int i =0; 

        while(i<n){
            string temp ="";
            while(s[i] == ' ' && i<n){
                i++;
            }
            while(s[i]!= ' ' && i<n){
                temp = temp + s[i];
                i++;
            }
            if(temp.size()>0){
                if(ans.size() == 0){
                    ans = temp;
                }
                else{
                    ans = temp + " " + ans;
                }
            }
        }
        return ans;
    }
};